

package cn.shengchao.examstart.medialibrary.acl.adapters.repositories;

import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstart.medialibrary.acl.ports.repositories.IFileRepository;
import cn.shengchao.examstart.medialibrary.domain.valobj.TaskTypeEnum;
import cn.shengchao.examstart.medialibrary.infrastructure.dao.FileDao;
import cn.shengchao.examstart.medialibrary.infrastructure.dao.FileTaskDao;
import cn.shengchao.examstart.medialibrary.infrastructure.dao.po.TFile;
import cn.shengchao.examstart.medialibrary.infrastructure.dao.po.TFileTask;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class FileRepository implements IFileRepository {

    @Autowired
    private FileTaskDao fileTaskDao;

    @Autowired
    private FileDao fileDao;

    @Override
    public TFileTask getFileTaskId(Long fileId) {
        TFileTask fileTask = fileTaskDao.selectOne(new LambdaQueryWrapper<TFileTask>().eq(TFileTask::getFileId, fileId));
        if (fileTask == null) {
            return null;
        }
        return fileTask;
    }

    @Override
    public Long getFileByUrl(String videoUrl) {
        if (StrUtil.isEmpty(videoUrl)) {
            return null;
        }
        if (videoUrl.contains("?")) {
            videoUrl = videoUrl.split("\\?")[0];
        }
        if (videoUrl.contains("m3u8")) {
            videoUrl = videoUrl.replace("m3u8", "mp4");
        }
        TFile tFile = fileDao.selectOne(new LambdaQueryWrapper<TFile>().eq(TFile::getUrl, videoUrl).last("limit 1"));
        if (tFile == null) {
            return null;
        }
        return tFile.getId();
    }

    @Override
    public void updateFileTaskId(Long fileId, String taskId) {
        TFileTask tFileTask = new TFileTask();
        tFileTask.setFileId(fileId);
        tFileTask.setTaskId(taskId);
        tFileTask.setTaskType(TaskTypeEnum.VIDEO_AI_TASK);
        fileTaskDao.insert(tFileTask);
    }

    @Override
    public void updateFileTaskId(TFileTask task) {
        fileTaskDao.updateById(task);
    }

    @Override
    public void delete(Long taskId) {
        fileTaskDao.deleteById(taskId);
    }

    @Override
    public List<TFile> getAllTackNotBrieflyIsNull() {
        MPJLambdaWrapper<TFile> wrapper = new MPJLambdaWrapper<TFile>()
                .selectAll(TFile.class)
                .leftJoin(TFileTask.class, TFileTask::getFileId, TFile::getId)
                .isNull(TFileTask::getBriefly)
                .eq(TFile::getExtension, "mp4")
                .eq(TFile::getType, 4);
        return fileDao.selectList(wrapper);
    }

    @Override
    public TFile getFile(long fileId) {
        return fileDao.selectById(fileId);
    }
}
